import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mobile.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/model/image_base.dart';

class RandomMageList extends StatefulWidget {
  final int format;
  final int screen;
  const RandomMageList({super.key, required this.format, required this.screen});

  @override
  State<RandomMageList> createState() => _RandomMageListState();
}

class _RandomMageListState extends State<RandomMageList> {
  final List<ImageBase> imgs = [];
  bool isLoading = false;
  int page = 1;
  int limit = 20;

  Future<void> getData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await mobileRandom(
          page: page,
          limit: limit,
          format: widget.format,
          screen: widget.screen);
      // 非标准json格式，手动解析
      Map<String, dynamic> data = json.decode(res.data);
      if (data['code'] == 1) {
        for (var i = 0; i < data['data'].length; i++) {
          imgs.add(ImageBase(
            largePath: data['data'][i]['url'],
            smallPath: data['data'][i]['url'],
            tags:
                data['data'][i]['tag'].replaceAll('#', '').replaceAll('默认', ''),
          ));
        }
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ImageList(
        imageList: imgs,
        isLoading: isLoading,
        isPC: widget.screen == 1,
        onImageBottomLoading: () {
          page++;
          getData();
        },
        onImageListRefresh: () {
          setState(() {
            page = 1;
            imgs.clear();
          });
          getData();
        });
  }
}
